package io.renren.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.renren.modules.substation.entity.TBaseDictInfoEntity;
import io.renren.modules.substation.service.TBaseDictInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.Properties;

@Component
public class SocketClient {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected TBaseDictInfoService tBaseDictInfoService;

    private static SocketClient socketClient;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        socketClient = this;
        socketClient.tBaseDictInfoService = this.tBaseDictInfoService;
    }

    private static class SingletonHolder {
        static final SocketClient instance = new SocketClient();
    }
    public static SocketClient getInstance(){
        return SingletonHolder.instance;
    }

    private EventLoopGroup group;
    private Bootstrap b;
    private ChannelFuture cf ;

    private SocketClient(){
        group = new NioEventLoopGroup();
        b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new ReadTimeoutHandler(5));
                        sc.pipeline().addLast(new ClientHandler());
                    }
                });
    }
    public void connect(){
        String server="127.0.0.1";
        int serverPort = 8888;
        try {

            List<TBaseDictInfoEntity> listDict2 = socketClient.tBaseDictInfoService.queryByDictKey("ALRAM_OUT_SWITCH");
            if(listDict2 != null){
                if(listDict2.get(0).getDictValue().length() > 0){
                    if(listDict2.get(0).getDictValue().equals("0")){
                        logger.debug("外送告警不启用");
                        return;
                    }
                }
            }

            List<TBaseDictInfoEntity> listDict = socketClient.tBaseDictInfoService.queryByDictKey("ALRAM_OUT_URL");
            String[] strs = new String[0];
            if(listDict != null){
                if(listDict.get(0).getDictValue().length() > 0){
                    logger.debug("ALRAM_OUT_URL:"+listDict.get(0).getDictValue());
                    strs = listDict.get(0).getDictValue().split(":");
                    if(strs[0].length() > 0 && strs[0] != null){
                        server = strs[0];
                        logger.debug("外送告警的IP："+server);
                    }

                    if(strs[1].length() > 0 && strs[1] != null){
                        serverPort = Integer.parseInt(strs[1]);
                        logger.debug("外送告警的端口："+serverPort);
                    }
                }else{
                    logger.debug("不存在告警外送配置 ALRAM_OUT_URL");
                }
            }

//            Properties properties = new Properties();
//            // 使用InPutStream流读取properties文件
//            BufferedReader bufferedReader = new BufferedReader(new FileReader("IPconfig.properties"));
//            if (bufferedReader != null) {
//                // 获取key对应的value值
//                properties.load(bufferedReader);
//                logger.debug("properties size:"+properties.size());
//                server = properties.getProperty("SERVER");
//                if (server != null) {
//                    logger.debug("SERVER：" + server);
//                } else {
//                    logger.debug("SERVER 配置为空 ");
//                }
//                String portStr = properties.getProperty("SERVER_PORT");
//                if (portStr != null) {
//                    logger.debug("SERVER_PORT：" + portStr);
//                    serverPort = Integer.parseInt(portStr);
//                } else {
//                    logger.debug("SERVER_PORT 配置为空 ");
//                }
//            } else {
//                logger.debug("server 配置为空 ");
//            }
        }catch (Exception e){
            logger.debug("告警外送配置ALRAM_OUT_URL异常，拒绝链接格式[0.0.0.0:8088]");
        }

        try {

            this.cf = b.connect(server, serverPort).sync();
            logger.debug("远程服务器已经连接, 可以进行数据交换..addr[" + server + "]port[" + serverPort + "]");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public ChannelFuture getChannelFuture(){
        //如果管道没有被开启或者被关闭了，那么重连
        if(this.cf == null){
            this.connect();
        }
        if(!this.cf.channel().isActive()){
            this.connect();
        }
        return this.cf;
    }
}
